package com.tjoris.midigateway;

import java.util.Properties;

import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;

class MidiModel extends AbstractTableModel {
	private static final long serialVersionUID = 1L;
	
	private static final int kCOLUMN_NAME = 0;
	private static final int kCOLUMN_NOTE = 1;
	private static final int kCOLUMN_COUNT = 2;
	
	private MidiEntry[] fEntries;
	
	
	public MidiModel(final IMidiAction[] actions, final Properties properties) {
		fEntries = new MidiEntry[actions.length];
		for (int i = 0; i < fEntries.length; ++i) {
			fEntries[i] = new MidiEntry(actions[i], properties);
		}
	}
	
	public void storeProperties(final Properties properties) {
		for (int i = 0; i < fEntries.length; ++i) {
			final String note = fEntries[i].getNote();
			if (note != null) {
				properties.put(fEntries[i].getAction().getID(), note);
			}
		}
	}
	
	public void setNote(final int rowIndex, final String note) {
		SwingUtilities.invokeLater(new Runnable () {
			public void run() {
				fEntries[rowIndex].setNote(note);
				fireTableCellUpdated(rowIndex, 1);
			}
		});
	}
	
	public int getRowForNote(final String note) {
		for (int i = 0; i < fEntries.length; ++i) {
			if (note.equals(fEntries[i].getNote())) {
				return i;
			}
		}
		return -1;
	}
	
	public IMidiAction getAction(final int rowIndex) {
		return fEntries[rowIndex].getAction();
	}
	
	@Override
	public Class<?> getColumnClass(final int columnIndex) {
		return String.class;
	}
	
	@Override
	public String getColumnName(final int column) {
		switch (column)
		{
			case kCOLUMN_NAME:
				return "Action";
			case kCOLUMN_NOTE:
				return "Note";
			default:
				assert false: "unknown column: " + column;
		}
		return null;
	}
	
	public int getColumnCount() {
		return kCOLUMN_COUNT;
	}

	public int getRowCount() {
		return fEntries.length;
	}

	public Object getValueAt(final int rowIndex, final int columnIndex) {
		switch (columnIndex)
		{
			case kCOLUMN_NAME:
				return fEntries[rowIndex].getName();
			case kCOLUMN_NOTE:
				return fEntries[rowIndex].getNote();
			default:
				assert false: "unknown column: " + columnIndex;
		}
		return null;
	}
}
